package leetcode_1_200;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LeeCode_99_2 {
    public static void main(String[] args) {
//        recoverTree(new TreeNode(3, new TreeNode(1), new TreeNode(4, new TreeNode(2), null)));
//        recoverTree(new TreeNode(1, new TreeNode(3, null, new TreeNode(2)), null));
//          recoverTree(new TreeNode(2, null, new TreeNode(1)));
//          recoverTree(new TreeNode(2, new TreeNode(3), new TreeNode(1)));
//
          TreeNode t = new TreeNode(146);
          t.left = new TreeNode(71);
          t.left.left = new TreeNode(55);
          t.left.left.left = new TreeNode(321);
          t.left.left.left.left = new TreeNode(-33);
          t.right = new TreeNode(-13);
          t.right.right = new TreeNode(399);
          t.right.left = new TreeNode(231);
          recoverTree(t);
    }

    private static void recoverTree(TreeNode root) {
        List<TreeNode> ns = new ArrayList<>();
        List<TreeNode> list = new ArrayList<>();
        helper(root, list);
        for (int i = 0; i < list.size() - 1; i++) {
            if (list.get(i).val > list.get(i + 1).val){
                ns.add(list.get(i));
                ns.add(list.get(i + 1));
            }
        }
        if (ns.size() == 2){
            int tmp = ns.get(0).val;
            ns.get(0).val = ns.get(1).val;
            ns.get(1).val = tmp;
        }else {
            int tmp = ns.get(0).val;
            ns.get(0).val = ns.get(3).val;
            ns.get(3).val = tmp;
        }
        System.out.println();
    }

    private static void helper(TreeNode node,List<TreeNode> list) {
        if (node == null)
            return;
        if (node.left == null) {
            list.add(node);
            helper(node.right,list);
            return;
        }
        helper(node.left, list);
        list.add(node);
        helper(node.right, list);
    }


    private static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
